import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:flutterdemo/1demo/common/utils/local_storage_util.dart';
import 'package:flutterdemo/1demo/common/utils/log_util.dart';
import 'package:flutterdemo/1demo/constants/color_constants.dart';
import 'package:flutterdemo/1demo/constants/string_constants.dart';
import 'package:flutterdemo/1demo/model/login_response_data.dart';
import 'package:flutterdemo/1demo/network/http_manager.dart';
import 'package:flutterdemo/1demo/network/result_data.dart';

class LoginWebPage extends StatefulWidget {
  @override
  _LoginWebPageState createState() => _LoginWebPageState();
}

class _LoginWebPageState extends State<LoginWebPage> {
  FlutterWebviewPlugin _flutterWebviewPlugin = FlutterWebviewPlugin();

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // 监听url变化
    _flutterWebviewPlugin.onUrlChanged.listen((url) async {
      // https://www.oschina.net/action/oauth2/authorize?response_type=code&client_id=dF2dm0WT8eBDjGbNefZH&redirect_uri=www.tupobi.top
      print("onUrlChanged:$url");
      setState(() {
        mounted ? _isLoading = false : _isLoading = true;
      });
      // https://www.oschina.net/action/oauth2/www.tupobi.top?code=zhXx7o&state=
      if (url != null && url.length > 0 && url.contains("?code=")) {
        String code = url.split('?')[1].split('&')[0].split('=')[1];
        print("code == $code");
        Map<String, dynamic> param = Map();
        param['client_id'] = AppInfo.APP_ID;
        param['client_secret'] = AppInfo.APP_PRIVATE_KEY;
        param['grant_type'] = "authorization_code";
        param['redirect_uri'] = AppInfo.CALLBACK_ADDRESS;
        param['code'] = code;
        param['dataType'] = "json";
        ResultData res = await HttpManager.getInstance(baseUrl: "").get(AppUrls.OAUTH2_TOKEN, param);
        LoginResponseData responseData = LoginResponseData.fromJson(res.data);
        LogUtil.v("token == " + responseData.accessToken);

        Map<String, dynamic> params = Map();
        params[LocalData.ACCESS_TOKEN] = responseData.accessToken;
        params[LocalData.REFRESH_TOKEN] = responseData.refreshToken;
        params[LocalData.TOKEN_TYPE] = responseData.tokenType;
        params[LocalData.EXPIRES_IN] = responseData.expiresIn;
        params[LocalData.UID] = responseData.uid;
        LocalData.saveLoginResponseData(params);
        // 弹出当前路由并返回refresh通知刷新
        Navigator.pop(context, 'refresh');
        String accessToken = await LocalStorageUtil.getString(LocalData.ACCESS_TOKEN);
        print("saved_access_token == $accessToken");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
//    response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
    return WebviewScaffold(
      url: AppUrls.OAUTH2_AUTHORIZE +
          '?response_type=code&client_id=' +
          AppInfo.APP_ID +
          '&redirect_uri=' +
          AppInfo.CALLBACK_ADDRESS,
      appBar: AppBar(
        title: Row(
          children: <Widget>[
            Text(
              "login",
              style: TextStyle(color: Color(AppColors.WHITE)),
            ),
            SizedBox(
              width: 10,
            ),
            _isLoading ? CupertinoActivityIndicator() : Container(),
          ],
        ),
      ),
      withJavascript: true,
      // 允许执行js
      withLocalStorage: true,
      // 允许本地存储
      withZoom: true, // 允许网页缩放
    );
  }

  @override
  void dispose() {
    super.dispose();
    _flutterWebviewPlugin.close();
    _flutterWebviewPlugin.dispose();
  }
}
